<template>
  <div class="recorder">
    <button @click="startRecording" :disabled="isRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <button @click="playRecording" :disabled="!recordedBlob">播放录音</button>
    <button @click="convertToSpeech" :disabled="!recordedBlob">转换为语音</button>
	{{JSON.stringify(this.recordedBlob)}}
  </div>
</template>

<script>
export default {
  data() {
    return {
      isRecording: false,
      mediaRecorder: null,
      chunks: [],
      recordedBlob: null,
    };
  },
  methods: {
    startRecording() {
      navigator.mediaDevices.getUserMedia({ audio: true })
        .then((stream) => {
          this.isRecording = true;
          this.chunks = [];
          this.mediaRecorder = new MediaRecorder(stream);
          this.mediaRecorder.addEventListener('dataavailable', (event) => {
            this.chunks.push(event.data);
          });
          this.mediaRecorder.start();
        })
        .catch((error) => {
          console.error('无法访问麦克风:', error);
        });
    },
    stopRecording() {
      if (this.mediaRecorder && this.isRecording) {
        this.mediaRecorder.addEventListener('stop', () => {
          this.isRecording = false;
          const blob = new Blob(this.chunks, { type: 'audio/mp3' });
          this.recordedBlob = blob;
          console.log('录音已保存',this.recordedBlob,JSON.stringify(this.recordedBlob));
        });
        this.mediaRecorder.stop();
      }
    },
    playRecording() {
      if (this.recordedBlob) {
        const audio = new Audio(URL.createObjectURL(this.recordedBlob));
        audio.play();
      }
    },
    convertToSpeech() {
      if (this.recordedBlob) {
        const audioContext = new AudioContext();
        const fileReader = new FileReader();
        fileReader.onload = (event) => {
          const arrayBuffer = event.target.result;
          audioContext.decodeAudioData(arrayBuffer)
            .then((audioBuffer) => {
              const audioBufferSource = audioContext.createBufferSource();
              audioBufferSource.buffer = audioBuffer;
              audioBufferSource.connect(audioContext.destination);
              audioBufferSource.start();
            })
            .catch((error) => {
              console.error('解码音频数据出错:', error);
            });
        };
        fileReader.readAsArrayBuffer(this.recordedBlob);
      }
    },
  },
};
</script>